package com.itheima.filter;

import com.itheima.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //执行放行的条件:session中取登陆者信息,如果有这个值,则表示已经登陆过了
        //将不必要的资源放行
        String uri = req.getRequestURI();
        //截取出
        String path = uri.substring(uri.lastIndexOf("/"));
        if ("/login.jsp".equals(path) || "/login".equals(path)) {
            filterChain.doFilter(req, resp);//放行
            return;
        }
        //获取session对象
        HttpSession session = req.getSession();
        //从session中获取user
        User user = (User) session.getAttribute("user");
        if (user != null) {
            //登陆成功
            filterChain.doFilter(req, resp);//放行
            return;
        }
        //未登录
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}
